import 'package:flutter/material.dart';
import 'package:life_milestones/MS-Model/MS-milestone.dart';
import 'package:life_milestones/controller/MS-global-user-controller.dart';
import 'package:life_milestones/util/MS-database-util.dart';

class MSMileStoneController extends ChangeNotifier{
  Map<int,List<MSMileStone>> _milestones = {};
  Map<int,List<MSMileStone>> get milestones =>_milestones;
  set milestones(Map<int,List<MSMileStone>> value){
    _milestones = value;
    notifyListeners();
  }

  refreshMilestoneList()async{
    await MSDatabaseUtil().query("Milestone",["id","month","type","content","userId"], ["userId"],[MSGlobalUserController().user!.userId!]).then((value){
      Map<int,List<MSMileStone>> temp = {};
      value?.forEach((element) {
        var stone = MSMileStone.fromJson(element);
        if(temp.containsKey(stone.month)){
          temp[stone.month]!.add(stone);
        }else{
          temp[stone.month] = [stone];
        }
      });
      milestones = temp;
    });
  }

  addMileStone(MSMileStone stone)async{
    await MSDatabaseUtil().insert("Milestone", stone.toJson());
    refreshMilestoneList();
  }

  deleteMileStone(MSMileStone stone)async{
    await MSDatabaseUtil().delete("Milestone",["id"],[stone.id]);
    refreshMilestoneList();
  }

  onLogout()async{
    milestones = {};
  }

  onDelete()async{
    await MSDatabaseUtil().delete("Milestone",["userId"],[MSGlobalUserController().user!.userId!]);
  }
}